package br.ufmg.ubicomp.droidguide.application;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.logging.Level;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import br.ufmg.ubicomp.droidguide.R;
import br.ufmg.ubicomp.droidguide.common.DroidGuideConfigurationManager;
import br.ufmg.ubicomp.droidguide.common.DroidGuideConstants;
import br.ufmg.ubicomp.droidguide.eventservice.DroidGuideEventServiceFactory;
import br.ufmg.ubicomp.droidguide.eventservice.DroidGuideServerRequestService;
import br.ufmg.ubicomp.droidguide.eventservice.notification.DGNotification;
import br.ufmg.ubicomp.droidguide.eventservice.notification.DGNotificationType;
import br.ufmg.ubicomp.droidguide.eventservice.notification.NotificationBucket;
import br.ufmg.ubicomp.droidguide.utils.AndroidUtils;

public class Login extends Activity {

    private static final Uri URI_DROIDGUIDE_USER = Uri.fromParts("content://", "droidguide/", "user/");
    
    EditText login, senha;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		Button loginButton = (Button) findViewById(R.id.login);
		loginButton.setOnClickListener(new LoginViewOnClickListener(this));

		initializeVariables();
	}

	private void initializeVariables() {
		String url = 
    		getResources().getText(R.string.serverUrl).toString();
		DroidGuideConfigurationManager.getInstance().addData(DroidGuideConstants.SERVER, url);

		String notificationLevel = getResources().getText(R.string.notificationLevel).toString();
		DroidGuideConfigurationManager.getInstance().addData(DroidGuideConstants.NOTIFICATION_LEVEL, notificationLevel);
		
		String deviceName = getResources().getText(R.string.deviceName).toString();
		DroidGuideConfigurationManager.getInstance().addData(DroidGuideConstants.DEVICE_NAME, deviceName);
		
		String updateInterval = getResources().getText(R.string.userEventUpdateInterval).toString();
		DroidGuideConfigurationManager.getInstance().addData(DroidGuideConstants.UPDATE_INTERVAL, updateInterval);
		
		AndroidUtils.showNotification(this, "Conn", AndroidUtils.getConnectivityInfo(this), 
				DGNotificationType.OUTGOING, "Login");
		
		login = (EditText) findViewById(R.id.widget30);
		senha = (EditText) findViewById(R.id.widget32);
		
	}

	class LoginViewOnClickListener implements OnClickListener{

		private Activity activity;
		
		public LoginViewOnClickListener(Activity activity) {
			this.activity = activity;
		}
		
		@Override
		public void onClick(View view) {
        	Context ctx = view.getContext();
        	EditText login = (EditText) findViewById(R.id.widget30);
        	String email = login.getText().toString();
        	EditText senha = (EditText) findViewById(R.id.widget32);
        	String pw = senha.getText().toString();
        	
        	executeLogin(view, login, email, senha);        	
			
		}
		
	}
	
	private void saveUserDataInContentProvider(Map<String, String> mapa) {
		// store this data into a content provider
    	Log.i("Login", mapa.toString());
    	String uri = "content://droidguide/user/";
    	ContentValues cv = new ContentValues();
    	cv.put("DG_KEY", mapa.get("DroidGuideUser"));
    	cv.put("DEV_KEY", mapa.get("Device"));
    	cv.put("LOC_KEY", mapa.get("Location"));
    	
    	getContentResolver().insert(URI_DROIDGUIDE_USER, cv);
	}
	
	private void showNotification(Map<String, String> mapa, String user)
	{
		String key = mapa.get("DroidGuideUser");
    	AndroidUtils.showNotification(this, "Login", "user " + user + " online.", 
    			DGNotificationType.INCOMMING, "DroidGuide.AppSpot");
    	DGNotification not = new DGNotification(DGNotificationType.APPLICATION, System.currentTimeMillis(), 
    			key, "Login");
    	
    	DroidGuideConfigurationManager.getInstance().addData("droidGuideUserKey", key);
    	
    	NotificationBucket.getInstance().add(not);
	}
	
	private String getConnectivityName()
	{
		return AndroidUtils.getConnectivityName(this);		
	}

	private void executeLogin(View view, EditText login, String email,
			EditText senha) {
		
		// we still need to transform this into a service
		DroidGuideServerRequestService service = DroidGuideEventServiceFactory.getServerRequestService();
		
		Map<String, String> mapa;
		try {
			String connectivityName = getConnectivityName();
			mapa = service.executeLogin(email, 
					DroidGuideConfigurationManager.getInstance().getData(DroidGuideConstants.DEVICE_NAME), 
					connectivityName);
			//saveUserDataInContentProvider(mapa);
			showNotification(mapa, email);
			String connectivityInfo = AndroidUtils.getConnectivityInfo(this);
			DroidGuideConfigurationManager.getInstance().addData("conn", connectivityInfo);
			AndroidUtils.showNotification(this, "Conn", 
					connectivityInfo, DGNotificationType.OUTGOING, "Login");
			Intent i = new Intent(view.getContext(),br.ufmg.ubicomp.droidguide.application.Main.class);
			startActivity(i);
			login.setText("");
			senha.setText("");
			finish();
		} catch (IOException e) {
			e.printStackTrace();
			String message = null;
			if (e instanceof MalformedURLException)
			{
				message = "Server URL is invalid: " + DroidGuideConfigurationManager.getInstance().getData(DroidGuideConstants.SERVER);
			}
			AndroidUtils.notifyError(message, this, "Login");
		}
	}
}